<?php
namespace control;
// 资产处置明细
class assetCutMxClass extends adIndexClass
{
    private const page  = 'assetCutMx'; # 权限
    private const table = 'asset_cut'; # 数据表
    private const tableMx = 'asset_cut_detail'; # 子表
    private const title = '资产处置明细';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'date'          => [
                        'name'  => "处置日期",
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'code'          => [
                        'name'  => "卡片编码",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'name'  => [
                        'name'  => '名称',
                        'width' => 150,
                    ],
                    'brand'         => [
                        'name'  => '品牌',
                        'width' => 150,
                    ],
                    'model'          => [
                        'name'  => '规格型号',
                        'width' => 150,
                    ],
                    'num'          => [
                        'name'  => '清理数量',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'salvage'          => [
                        'name'  => '资产残值('.static::$unit.')',
                        'width' => 100,
                    ],
                    'income'          => [
                        'name'  => '清理收入',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'fee'          => [
                        'name'  => '清理费用',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'text'          => [
                        'name'  => '备注',
                        'width' => 150,
                    ],
                    'type'          => [
                        'name'  => '处置方式',
                        'width' => 100,
                    ],
                    'orderNo'          => [
                        'name'  => '处置单号',
                        'width' => 150,
                        'sort' => 1,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "卡片编码" => text(array("name" => "cOrderNo")),
                    "名称" => text(array("name" => "name")),
                    "处置方式" => text(array("name" => "type")),
                ],
                [
                    "处置单号" => text(array("name" => "orderNo")),
                    "处置日期" => text(
                        [
                            'name' => 'date',
                            'laydate' => ['range' => '~', 'type' => 'date'],
                        ]
                    ),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*固定资产入口页*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "export")) {
            $button .= "<a href='" . root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=exportData' class='spanButton'>导出</a>\n";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*固定资产列表*/
    public function homeSearch()
    {
        //查询结果
        $and = '';

        if ($this->post('date')) {
            $and .= self::timeComparison($this->post('date'), 'date', 'b.date');
        }
        //主表查询
        $where   = search([
            "like" => [
                'b.orderNo'    => $this->post('orderNo'),
                'c.name'    => $this->post('name'),
                'c.orderNo'    => $this->post('cOrderNo'),
            ],
            "=" => [
                'b.type'    => $this->post('type'),
                'b.coid'=>self::$coid
            ]
        ]).$and;
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'b.date desc,a.list',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        $page = $this->page([
            "table" => self::tableMx." as a join ".self::table.' as b on a.orderId = b.id join asset as c on c.id = a.atid',
            "where" => $where,
            'field'=>"a.*,b.date,c.name,c.brand,c.model,b.type,b.orderNo,c.orderNo as code",
            "order" => $orderBy['orderBy']
        ]);
        $_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array();
        $url = root.'control/adIndex.html?cla=assetCut&fun=detail&id=';
        //获取记录
        foreach ($page['array'] as $array) {
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'code':
                        $row[] = componentClass::urlTitle($array['code'],root.'control/adIndex.html?cla=assetList&fun=detail&id='.$array['atid'],'资产卡片');
                        break;
                    case 'salvage':
                        $endDate = $array['date'];
                        $asset = query('asset', " id = '$array[atid]'");
                        $ratio = assetManagementClass::monthRatio($asset['depreciationMethod'],$asset['discountYear'],$asset['money'],$asset['purchaseMoney'],$asset['depreciationMoney'],$asset['purchaseDate'],$endDate,1);
                        $monthDecMoney =assetManagementClass::monthDecMoney($asset['depreciationMethod'],$asset['purchaseMoney'],$ratio/100,$asset['purchaseDate'],$endDate,$asset['discountYear'],$asset['money'],$asset['depreciationMoney']);
                        $discountMoney = assetManagementClass::calcSalvage($asset['depreciationMethod'],$monthDecMoney,$asset['purchaseDate'],$asset['discountYear'],$asset['purchaseMoney'],$asset['money'],$asset['depreciationMoney'],$endDate);
                        $row[] = round($asset['purchaseMoney']-$discountMoney,2);
                        break;
                    case 'orderNo':
                        $row[] = componentClass::urlTitle($array['orderNo'],$url.$array['orderId'],'资产处置');
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }


    /**
     * 导出
     */
    public function exportData()
    {
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        } else {
            $data = [];
            $sql = $_SESSION[self::page]['sql'];
            $title = ['处置日期', '卡片编码', '名称', '品牌', '规格型号', '清理数量', '资产残值('.static::$unit.')', '清理收入', '清理费用', '备注', '处置方式', '处置单号'];
            $result = self::sqlFind($sql);
            if (is_array($result['array'])) {
                foreach ($result['array'] as $array) {
                    $endDate = $array['date'];
                    $asset = query('asset', " id = '$array[atid]'");
                    $ratio = assetManagementClass::monthRatio($asset['depreciationMethod'],$asset['discountYear'],$asset['money'],$asset['purchaseMoney'],$asset['depreciationMoney'],$asset['purchaseDate'],$endDate,1);
                    $monthDecMoney =assetManagementClass::monthDecMoney($asset['depreciationMethod'],$asset['purchaseMoney'],$ratio/100,$asset['purchaseDate'],$endDate,$asset['discountYear'],$asset['money'],$asset['depreciationMoney']);
                    $discountMoney = assetManagementClass::calcSalvage($asset['depreciationMethod'],$monthDecMoney,$asset['purchaseDate'],$asset['discountYear'],$asset['purchaseMoney'],$asset['money'],$asset['depreciationMoney'],$endDate);

                    //本列
                    $data[] = [
                        $array['date'], componentClass::urlTitle($array['code'],root.'control/adIndex.html?cla=assetList&fun=detail&id='.$array['atid'],'资产卡片'), $array['name'], $array['brand'], $array['model'], $array['num'], round($asset['purchaseMoney']-$discountMoney,2), $array['income'],$array['fee'],zishu($array['text'],20), $array['type'], componentClass::urlTitle($array['orderNo'],$url.$array['orderId'],'资产处置')
                    ];
                }
            }
            $text = $this->control['name'] . "导出了" . self::title;
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, self::title . ".xlsx");
        }
        header("Location:" . getenv("HTTP_REFERER"));
        exit(0);
    }
}
